package com.eastdigit.system.controller;

import com.eastdigit.servlet.Response;
import com.eastdigit.system.model.BusinessException;
import com.eastdigit.system.model.Constants;
import com.eastdigit.system.service.IFileService;
import com.eastdigit.util.DateUtil;
import com.eastdigit.util.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

@Controller
@RequestMapping(value = "file")
public class FileController {

    @Autowired
    private IFileService fileService;

    @RequestMapping("/upload")
    @ResponseBody
    public JSONObject upload(MultipartFile file) throws Exception {
        return Response.response(fileService.saveFile(file, null));
    }

    @RequestMapping("/uploadEx")
    @ResponseBody
    public JSONObject uploadWithData(MultipartFile file, HttpServletRequest request) throws Exception {
        JSONObject jsonObject = new JSONObject();
        String url = fileService.saveFile(file, request.getParameter("uploadDir"));
        String name = request.getParameter("name");
        String type = request.getParameter("type");

        jsonObject.put("name", name);
        jsonObject.put("type", fileService.getFileType(type, name));
        jsonObject.put("size", request.getParameter("size"));
        jsonObject.put("path", url);
        jsonObject.put("url", Constants.SERVER + "file/content.do?path=" + url + "&filename=" + name);
        jsonObject.put("author", request.getParameter("author"));
        jsonObject.put("time", DateUtil.getCurrentDateTime());
        return Response.response(jsonObject);
    }

    @RequestMapping("/ajaxFileUpload")
    @ResponseBody
    public String ajaxFileUpload(@RequestParam(value = "file") MultipartFile file) throws Exception {
        return upload(file).toString();
    }

    @RequestMapping("/uploadClient")
    @ResponseBody
    public JSONObject uploadClient(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> fileList = multipartRequest.getFiles("file");
        if (fileList.size() > 0) {
            return Response.response(fileService.saveFile(fileList.get(0), null));
        } else {
            throw new BusinessException("获取文件失败！");
        }
    }

    @RequestMapping(value = "/content")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String path = request.getParameter("path");
        if (path.contains("..")) {
            throw new BusinessException("非法访问！");
        }
        if (StringUtil.isNotEmpty(path)) {
            String filename = request.getParameter("filename");// 这里都是中文乱码，nginx能够识别
            if (Constants.NGINX_CONTROL) {// nginx管理的文件
                String url = Constants.NGINX + path;
                if (StringUtil.isNotEmpty(filename)) {
                    url += "?filename=" + filename;
                }
                response.sendRedirect(url);// 转发给nginx
            } else {// 系统管理
                String filePath = Constants.ATTACHMENT_PATH + path;
                File file = new File(filePath);
                if (!file.exists()) {
                    throw new BusinessException("文件不存在！");
                }
                if (path.startsWith("image/")) {// 浏览图片
                    response.setContentType("image/jpeg");
                } else {
                    if (StringUtil.isEmpty(filename)) {// 设置了文件名
                        filename = file.getName();
                    }
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-disposition",
                            "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO8859-1"));
                }
                // 创建文件输入流
                FileInputStream is = new FileInputStream(file);
                // 响应输出流
                ServletOutputStream out = response.getOutputStream();
                // 创建缓冲区
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                is.close();
                out.flush();
                out.close();
            }
        }
    }
}
